import React, { useState, useRef, useEffect } from "react";
import {
  Input,
  Button,
  Avatar,
  Spin,
  message,
  Layout,
  Menu,
  Modal,
} from "antd";
import {
  SendOutlined,
  UserOutlined,
  RobotOutlined,
  PlusOutlined,
  DeleteOutlined,
  MessageOutlined,
} from "@ant-design/icons";
import Typed from "typed.js";
import "./style.css";

const { TextArea } = Input;
const { Sider, Content } = Layout;

interface Message {
  id: string;
  type: "user" | "assistant";
  content: string;
  timestamp: Date;
  isTyping?: boolean;
}

interface ChatSession {
  id: string;
  title: string;
  messages: Message[];
  createdAt: Date;
}

const AIChat: React.FC = () => {
  const [chatSessions, setChatSessions] = useState<ChatSession[]>([
    {
      id: "1",
      title: "新对话",
      messages: [
        {
          id: "1",
          type: "assistant",
          content: "你好！我是 AI 助手，有什么可以帮助你的吗？",
          timestamp: new Date(),
        },
      ],
      createdAt: new Date(),
    },
  ]);
  const [currentSessionId, setCurrentSessionId] = useState("1");
  const [inputValue, setInputValue] = useState("");
  const [loading, setLoading] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const typedRefs = useRef<{ [key: string]: Typed }>({});

  const currentSession = chatSessions.find(
    (session) => session.id === currentSessionId
  );

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();
  }, [currentSession?.messages]);

  // 清理 typed 实例
  useEffect(() => {
    return () => {
      Object.values(typedRefs.current).forEach((typed) => {
        if (typed) {
          typed.destroy();
        }
      });
    };
  }, []);

  const createNewChat = () => {
    const newSession: ChatSession = {
      id: Date.now().toString(),
      title: "新对话",
      messages: [
        {
          id: "1",
          type: "assistant",
          content: "你好！我是 AI 助手，有什么可以帮助你的吗？",
          timestamp: new Date(),
        },
      ],
      createdAt: new Date(),
    };
    setChatSessions((prev) => [newSession, ...prev]);
    setCurrentSessionId(newSession.id);
  };

  const deleteChat = (sessionId: string) => {
    Modal.confirm({
      title: "确认删除",
      content: "确定要删除这个对话吗？删除后无法恢复。",
      onOk: () => {
        const newSessions = chatSessions.filter(
          (session) => session.id !== sessionId
        );
        if (newSessions.length === 0) {
          createNewChat();
        } else {
          setChatSessions(newSessions);
          if (currentSessionId === sessionId) {
            setCurrentSessionId(newSessions[0].id);
          }
        }
        message.success("对话已删除");
      },
    });
  };

  const handleSend = async () => {
    if (!inputValue.trim() || !currentSession) {
      message.warning("请输入内容");
      return;
    }

    const userMessage: Message = {
      id: Date.now().toString(),
      type: "user",
      content: inputValue,
      timestamp: new Date(),
    };

    // 更新当前会话的消息
    const updatedSessions = chatSessions.map((session) =>
      session.id === currentSessionId
        ? {
            ...session,
            messages: [...session.messages, userMessage],
            title:
              session.title === "新对话"
                ? inputValue.slice(0, 20) + "..."
                : session.title,
          }
        : session
    );
    setChatSessions(updatedSessions);
    setInputValue("");
    setLoading(true);

    // 模拟 AI 回复
    setTimeout(() => {
      const fullResponse = `这是对"${userMessage.content}"的回复。我是模拟的 AI 助手，目前只能提供简单的回复。`;
      const assistantMessage: Message = {
        id: (Date.now() + 1).toString(),
        type: "assistant",
        content: "",
        timestamp: new Date(),
        isTyping: true,
      };

      // 使用最新的 sessions 状态
      setChatSessions((prevSessions) => {
        const sessionsWithAssistant = prevSessions.map((session) =>
          session.id === currentSessionId
            ? { ...session, messages: [...session.messages, assistantMessage] }
            : session
        );
        return sessionsWithAssistant;
      });
      setLoading(false);

      // 使用 typed.js 实现打字机效果
      setTimeout(() => {
        const element = document.querySelector(
          `[data-message-id="${assistantMessage.id}"] .message-text`
        ) as HTMLElement;
        if (element) {
          // 清理之前的实例
          if (typedRefs.current[assistantMessage.id]) {
            typedRefs.current[assistantMessage.id].destroy();
          }

          const typed = new Typed(element, {
            strings: [fullResponse],
            typeSpeed: 50,
            backSpeed: 0,
            loop: false,
            showCursor: true,
            cursorChar: "|",
            onComplete: () => {
              setChatSessions((prev) =>
                prev.map((session) =>
                  session.id === currentSessionId
                    ? {
                        ...session,
                        messages: session.messages.map((msg) =>
                          msg.id === assistantMessage.id
                            ? { ...msg, isTyping: false }
                            : msg
                        ),
                      }
                    : session
                )
              );
            },
          });

          typedRefs.current[assistantMessage.id] = typed;
        }
      }, 100);
    }, 1000);
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  const menuItems = chatSessions.map((session) => ({
    key: session.id,
    icon: <MessageOutlined />,
    label: (
      <div className="chat-menu-item">
        <span className="chat-title">{session.title}</span>
        <Button
          type="text"
          size="small"
          icon={<DeleteOutlined />}
          onClick={(e) => {
            e.stopPropagation();
            deleteChat(session.id);
          }}
          className="delete-btn"
        />
      </div>
    ),
  }));

  return (
    <Layout className="ai-chat-layout">
      <Sider width={300} className="chat-sider">
        <div className="sider-header">
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={createNewChat}
            block
          >
            新建对话
          </Button>
        </div>
        <Menu
          mode="inline"
          selectedKeys={[currentSessionId]}
          items={menuItems}
          onClick={({ key }) => setCurrentSessionId(key)}
          className="chat-menu"
        />
      </Sider>

      <Content className="chat-content">
        <div className="messages-container">
          {currentSession?.messages.map((msg) => (
            <div
              key={msg.id}
              data-message-id={msg.id}
              className={`message ${
                msg.type === "user" ? "user-message" : "assistant-message"
              }`}
            >
              <div className="message-avatar">
                <Avatar
                  icon={
                    msg.type === "user" ? <UserOutlined /> : <RobotOutlined />
                  }
                  style={{
                    backgroundColor:
                      msg.type === "user" ? "#1890ff" : "#52c41a",
                  }}
                />
              </div>
              <div className="message-content">
                <div className="message-text">{msg.content}</div>
                <div className="message-time">
                  {msg.timestamp.toLocaleTimeString()}
                </div>
              </div>
            </div>
          ))}
          {loading && (
            <div className="message assistant-message">
              <div className="message-avatar">
                <Avatar
                  icon={<RobotOutlined />}
                  style={{ backgroundColor: "#52c41a" }}
                />
              </div>
              <div className="message-content">
                <div className="message-text">
                  <Spin size="small" /> AI 正在思考中...
                </div>
              </div>
            </div>
          )}
          <div ref={messagesEndRef} />
        </div>

        <div className="input-container">
          <TextArea
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="输入你的问题..."
            autoSize={{ minRows: 2, maxRows: 4 }}
            disabled={loading}
          />
          <Button
            type="primary"
            icon={<SendOutlined />}
            onClick={handleSend}
            loading={loading}
            disabled={!inputValue.trim()}
            className="send-button"
          >
            发送
          </Button>
        </div>
      </Content>
    </Layout>
  );
};

export default AIChat;
